import { GameManager, IUpdatable, regGameManager } from "../GameManager";
import { GameStorage, regStorage } from "../GameStorage";

/**本地数据管理器 */
@regGameManager()
export class LocalStorageManager extends GameManager implements IUpdatable {

    private _storageMap: Map<Object, GameStorage<any>> = new Map()
    protected _updates: IUpdatable[] = [];

    public async initialize(): Promise<void> {
        //注册到regStorage中的类型列表
        const clzArr: any[] = (regStorage as any).clzArr
        if (clzArr) {
            for (let index = 0; index < clzArr.length; index++) {
                const clz=clzArr[index]
                const storage=this.regStorage(clz)
                storage.initialize && await storage.initialize()
            }
        }
    }

    regStorage(clz){
        const storage: GameStorage<any> = new clz()
        if ('update' in storage) {
            this._updates.push(storage as unknown as IUpdatable)
        }
        this._storageMap.set(clz, storage)
        return storage
    }

    /**获取一个存储仓库 */
    public storage<T extends GameStorage<any>>(storageClz: (new () => T)) {
        return this._storageMap.get(storageClz) as T
    }

    update(dt: number): void {
        this._updates.forEach((i) => {
            i.update(dt)
        })
        this.checkCrossDay()
    }

    /**检查是否跨天 */
    checkCrossDay() {
        const isCrossDay = false
        if (isCrossDay) {
            this._storageMap.forEach((storage) => {
                storage.onCrossDay()
            })
        }
    }
}